package com.suxin;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.Set;

/**
 * @author Tang
 * @classname MainClient
 * @description [  ]
 * @date 2021/3/4 11:23
 */
public class MainClient {

    private static final String host = "127.0.0.1";
    private static final Integer port = 9000;

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();
        SocketChannel socket = SocketChannel.open();
        socket.configureBlocking(false);
        socket.connect(new InetSocketAddress(host, port));
        SelectionKey register = socket.register(selector, SelectionKey.OP_READ);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        new Thread(() -> {
            while (true) {
                try {
                    selector.select();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    System.out.println("selectionKeys--->size--->" + selectionKeys.size() + " register--->" + register.interestOps());
                    selectionKeys.forEach(selectionKey -> {
                        System.out.println("isWritable--->" + selectionKey.isWritable());
                        System.out.println("isReadable--->" + selectionKey.isReadable());
                        try {
                            if (selectionKey.isWritable()) {
                                System.out.println("触发写操作....");
                                socket.write(byteBuffer);
                                byteBuffer.flip();
                                register.interestOps(SelectionKey.OP_READ);
                                selector.wakeup();
                            }
                            if (selectionKey.isReadable()) {
                                socket.read(byteBuffer);
                                byteBuffer.flip();
                                System.out.println("收到数据是:--->" + new String(byteBuffer.array()));
                            }
                            byteBuffer.clear();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String nextLine = scanner.nextLine();
            System.out.println("nextLine--->" + nextLine);
            byteBuffer.put(nextLine.getBytes());
            byteBuffer.flip();
            register.interestOps(SelectionKey.OP_WRITE);
        }
    }
}